﻿$(function () {
    var boggleViewModel = new BoggleViewModel();
    ko.applyBindings(boggleViewModel);
    
    //create boggle board grid
    var grid = $("#grid").handsontable({
        startRows: 3,
        startCols: 3,
        rowHeaders: false,
        colHeaders: false,
        contextMenu: true,
        //filter user input
        onBeforeChange: function (changes) {
            var newValueIndex = 3;
            var newValue = changes[0][newValueIndex].trim();
            var nonAlphaPattern = "[^a-z-A-z]";
            var matchResults = newValue.match(nonAlphaPattern);
            //accept the special case of the two letters combination Qu
            if(newValue === 'qu') {
                return true;
            }
            //don't accept changes that have non-alpha characters or if the change has more than one character
            else if (matchResults != null || newValue.length > 1) {
                alertUser('Error: You must enter a single alpha character or the combination qu');
                return false;
            } else {
                return true;
            }
        },
    });

    //make buttons pretty
    $(".button").button();

    $(".randomize").click(function () {
        var rowCount = grid.handsontable('countRows');
        var colCount = grid.handsontable('countCols');
        for (var row = 0; row < rowCount; row++) {
            for (var col = 0; col < colCount; col++) {
                grid.handsontable('setDataAtCell', row, col, generateRandomString(1));
            }
        }
    });

    var mapping = {
        'wordTraversals': {
            create: function (options) {
                return new BoggleTraversalViewModel(options.data, grid);
            }
        }
    };
    
    $(".solve").click(function() {
        var gridData = grid.handsontable('getData');

        //flatten grid to a one-dimensional array for post
        var gridData1D = $.map(gridData, function (row) {
            return row;
        });
        
        //check if the grid contains an empty space
        if (jQuery.inArray('', gridData1D) != -1) {
            alertUser('Every cell must be populated before the boggle board can be solved.');
            return false;
        }

        var boggleSolveModel = {
            letters: gridData1D,
            Height: grid.handsontable('countRows'),
            Width: grid.handsontable('countCols')
        };
        
        //block the UI to inform the user that a web request is being sent
        $.blockUI();
        $.ajax({
            url: "api/boggle/solve",
            type: "POST",
            contentType: "application/json",
            data: JSON.stringify(boggleSolveModel),
            success: function (boggleSolutionData) {
                $("#solutions-container").show();
                ko.mapping.fromJS(boggleSolutionData, mapping, boggleViewModel);
            }
        });
    });
});